package com.xuelang.pipeline.infrastructure.msg.repository;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuelang.jadp.client.sys.enums.DeleteFlag;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.msg.*;
import com.xuelang.pipeline.domain.msg.repository.MsgUserMessagesRepository;
import com.xuelang.pipeline.infrastructure.msg.dataobject.MsgMessageContentDO;
import com.xuelang.pipeline.infrastructure.msg.dataobject.MsgUserMessagesDO;
import com.xuelang.pipeline.infrastructure.msg.mapper.MsgMessageContentMapper;
import com.xuelang.pipeline.infrastructure.msg.mapper.MsgUserMessagesMapper;
import com.xuelang.sys.app.sys.utils.UserContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MsgUserMessagesRepositoryImpl implements MsgUserMessagesRepository {

    @Autowired
    MsgMessageContentMapper msgMessageContentMapper;

    @Autowired
    MsgUserMessagesMapper userMessagesMapper;

    @Override
    public PageRecord<UserMessageDTO> findUserMessagePageList(UserMessageQueryDTO queryDTO) {

        Page<MsgUserMessagesDO> page = new Page<>(queryDTO.getCurrentPage(), queryDTO.getPageSize());
        LambdaQueryWrapper<MsgUserMessagesDO> wrapper = Wrappers.lambdaQuery(MsgUserMessagesDO.class);

        if (StringUtils.isNotBlank(queryDTO.getReceiveUserId())) {
            wrapper.eq(MsgUserMessagesDO::getReceiveUserId, queryDTO.getReceiveUserId());
        }

        wrapper.orderByDesc(MsgUserMessagesDO::getCreateTime);

        Page<MsgUserMessagesDO> msgUserPage = userMessagesMapper.selectPage(page, wrapper);

        List<UserMessageDTO> list = null;
        if (msgUserPage != null && msgUserPage.getRecords() != null && msgUserPage.getRecords().size() > 0) {
            List<String> messageIdList = msgUserPage
                    .getRecords().stream()
                    .filter(e -> StringUtils.isNotBlank(e.getMessageContentId()))
                    .map(e -> e.getMessageContentId())
                    .collect(Collectors.toList());

            List<MsgMessageContentDO> msgMessageContentDOS = msgMessageContentMapper.selectBatchIds(messageIdList);


            List<UserMessageDTO> collect = msgUserPage.getRecords()
                    .stream()
                    .filter(e -> StringUtils.isNotBlank(e.getMessageContentId()))
                    .map(e -> {
                            UserMessageDTO dto = new UserMessageDTO();
                            BeanUtils.copyProperties(e, dto);

                            MsgMessageContentDO msgMessageContentDO = msgMessageContentDOS.stream().filter(s -> s.getId().equals(dto.getMessageContentId())).findAny().orElse(null);
                            if (msgMessageContentDO != null) {
                                MessageDTO msg = new MessageDTO();
                                BeanUtils.copyProperties(msgMessageContentDO, msg);
                                dto.setMessageDesc(msg);
                            }

                            return dto;
                        })
                    .collect(Collectors.toList());

            list = collect;

        }

        PageRecord resPage = new PageRecord();
        resPage.setCurrentPage(queryDTO.getCurrentPage().longValue());
        resPage.setPageSize(queryDTO.getPageSize().longValue());
        resPage.setTotalCount(msgUserPage.getTotal());
        resPage.setTotalPages(msgUserPage.getPages());
        resPage.setRecords(list);
        return resPage;
    }


    @Override
    public UserMessageSaveDTO saveMessage(UserMessageSaveDTO messageSaveDTO) {
        MsgMessageContentDO msgMessageContentDO = new MsgMessageContentDO();
        msgMessageContentDO.setId(IdUtil.simpleUUID());
        msgMessageContentDO.setTitle(messageSaveDTO.getTitle());
        msgMessageContentDO.setContent(messageSaveDTO.getContent());
        msgMessageContentDO.setTitleImage(messageSaveDTO.getTitleImage());
        msgMessageContentDO.setMsgType(messageSaveDTO.getMsgType());
        msgMessageContentDO.setCreateTime(new Date());
        msgMessageContentDO.setCreateBy(UserContextUtils.getUserId());
        msgMessageContentDO.setDelFlag(DeleteFlag.NOT_DELETE);

        msgMessageContentDO.setCreatorId(UserContextUtils.getUserId());
        msgMessageContentDO.setUpdaterId(UserContextUtils.getUserId());
        msgMessageContentDO.setUpdateTime(new Date());

        msgMessageContentMapper.insert(msgMessageContentDO);

        if (messageSaveDTO.getReceiveUserIds() != null && messageSaveDTO.getReceiveUserIds().size() > 0) {
            messageSaveDTO.getReceiveUserIds().forEach(uid -> {
                MsgUserMessagesDO userMsg = new MsgUserMessagesDO();
                userMsg.setId(IdUtil.simpleUUID());
                userMsg.setMessageContentId(msgMessageContentDO.getId());
                userMsg.setReceiveUserId(uid);
                userMsg.setDelFlag(DeleteFlag.NOT_DELETE);
                userMsg.setReadStatus(MsgConstant.MSG_NOT_READ);
                userMsg.setCreateTime(new Date());
                userMsg.setCreateBy(UserContextUtils.getUserId());

                userMsg.setCreatorId(UserContextUtils.getUserId());
                userMsg.setUpdaterId(UserContextUtils.getUserId());
                userMsg.setUpdateTime(new Date());

                userMessagesMapper.insert(userMsg);
            });

        }

        return messageSaveDTO;
    }

    @Override
    public List<UserMessageDTO> userTagsReadMessages(UserMessageReadMsgDTO readMsgDTO) {
        LambdaQueryWrapper<MsgUserMessagesDO> wrapper = Wrappers.lambdaQuery(MsgUserMessagesDO.class);
        wrapper.eq(MsgUserMessagesDO::getReceiveUserId,readMsgDTO.getReceiveUserId());
        wrapper.in(MsgUserMessagesDO::getMessageContentId,readMsgDTO.getMsgIds());
        List<MsgUserMessagesDO> msgUserMessagesDOS = userMessagesMapper.selectList(wrapper);

        List<UserMessageDTO> res = new ArrayList<>();

        if (msgUserMessagesDOS != null && msgUserMessagesDOS.size() > 0) {
            msgUserMessagesDOS.stream()
                    .filter(e -> e.getReadStatus() == MsgConstant.MSG_NOT_READ)
                    .forEach(e -> {
                        e.setUpdateBy(UserContextUtils.getUserId());
                        e.setUpdateTime(new Date());
                        e.setReadTime(new Date());
                        e.setReadStatus(MsgConstant.MSG_READ);

                        e.setUpdaterId(UserContextUtils.getUserId());
                        userMessagesMapper.updateById(e);
            });


            res = msgUserMessagesDOS.stream()
                    .map(e -> {
                        UserMessageDTO dto = new UserMessageDTO();
                        BeanUtils.copyProperties(e, dto);
                        return dto;
                    })
                    .collect(Collectors.toList());
        }
        return res;
    }


    @Override
    public Long getUserUnReadMessageCount(UserMessageReadMsgDTO readMsgDTO) {
        LambdaQueryWrapper<MsgUserMessagesDO> wrapper = Wrappers.lambdaQuery(MsgUserMessagesDO.class);
        wrapper.eq(MsgUserMessagesDO::getReceiveUserId,readMsgDTO.getReceiveUserId());
        wrapper.eq(MsgUserMessagesDO::getReadStatus,MsgConstant.MSG_NOT_READ);
        Long count = userMessagesMapper.selectCount(wrapper);
        return count;
    }
}
